<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>用户登录</h2>
        <p>在线商城购物系统</p>
      </div>
      
      <div class="login-form">
        <el-form
          :model="loginForm"
          :rules="loginRules"
          ref="loginFormRef"
          size="large"
          label-position="top"
        >
          <el-form-item label="用户名" prop="username">
            <el-input 
              v-model="loginForm.username" 
              placeholder="请输入用户名"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="密码" prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码"
              show-password
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <div class="remember-row">
            <el-checkbox v-model="remember">记住我</el-checkbox>
            <a href="javascript:;" class="forgot-link">忘记密码?</a>
          </div>
          
          <el-form-item>
            <el-button type="primary" class="login-button" @click="handleLogin" :loading="loading">
              {{ loading ? '登录中...' : '登 录' }}
            </el-button>
          </el-form-item>
          
          <div class="register-return-row">
            <div class="register-link">
              <span>还没有账号?</span>
              <router-link to="/register">立即注册</router-link>
            </div>
            
            <div v-if="redirectUrl" class="return-link">
              <el-button link type="primary" @click="handleReturn">
                <el-icon><Back /></el-icon> 返回商品页
              </el-button>
            </div>
          </div>
        </el-form>
      </div>
      
      <div class="login-footer">
        <p>Copyright © 2023 在线商城 All Rights Reserved.</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserWebLogin'
}
</script>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { User, Lock, Back } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import md5 from 'js-md5';

const router = useRouter();
const loginFormRef = ref(null);
const loading = ref(false);
const remember = ref(false);

// 获取重定向URL
const redirectUrl = computed(() => {
  return router.currentRoute.value.query.redirect;
});

const loginForm = reactive({
  username: '',
  password: ''
});

// 添加标题设置
document.title = '用户登录 - 在线商城';

const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});

// 返回上一页
const handleReturn = () => {
  if (redirectUrl.value) {
    router.push(redirectUrl.value);
  }
};

// 登录处理
const handleLogin = () => {
  if (loginFormRef.value) {
    loginFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        try {
          // 构建登录数据
          const loginData = {
            username: loginForm.username,
            password: md5(loginForm.password)
          };
          
          // 发送登录请求
          const response = await axios.post('http://localhost:9191/login', loginData);
          
          if (response.data && response.data.code === '200') {
            const userData = response.data.data;
            // 存储用户信息
            sessionStorage.setItem('user', JSON.stringify(userData));

            
            // 提示登录成功
            ElMessage.success('登录成功');
            
            // 检查是否有重定向地址
            const redirect = router.currentRoute.value.query.redirect;
            if (redirect) {
              // 如果有重定向地址，则跳转到该地址
              router.push(redirect);
            } else {
              // 否则跳转到首页
              router.push('/userWeb/index');
            }
          } else {
            ElMessage.error(response.data?.msg || '登录失败，请检查用户名和密码');
          }
        } catch (error) {
          console.error('登录请求错误:', error);
          ElMessage.error('登录失败，请稍后再试');
        } finally {
          loading.value = false;
        }
      } else {
        ElMessage.warning('请正确填写登录信息');
      }
    });
  }
};
</script>

<style scoped>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
}

.login-box {
  width: 420px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

.login-header {
  padding: 30px 20px;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.login-header h2 {
  margin: 0;
  font-size: 24px;
}

.login-header p {
  margin: 10px 0 0;
  font-size: 14px;
  opacity: 0.8;
}

.login-form {
  padding: 30px;
}

.remember-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-link {
  font-size: 14px;
  color: #409EFF;
  text-decoration: none;
}

.login-button {
  width: 100%;
  padding: 12px 15px;
  font-size: 16px;
}

.register-return-row {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.register-link {
  font-size: 14px;
}

.register-link span {
  color: #666;
}

.register-link a {
  margin-left: 5px;
  color: #409EFF;
  text-decoration: none;
}

.return-link {
  font-size: 14px;
}

.login-footer {
  padding: 15px;
  text-align: center;
  background-color: #f5f5f5;
  font-size: 12px;
  color: #666;
}
</style> 